package com.atguigu.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.SubjectExcelData;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
public class SubjectExcelDataListener extends AnalysisEventListener<SubjectExcelData> {

    // Autowired 从容器中获取组件类对象 ，只有组件类中才可以使用自动装配
    SubjectMapper subjectMapper;

    public SubjectExcelDataListener(SubjectMapper subjectMapper){
        this.subjectMapper = subjectMapper;
    }
    @Override
    public void invoke(SubjectExcelData subjectExcelData, AnalysisContext analysisContext) {
        //每一行数据都直接存到数据库
        //SubjectExcelData对象数据中包含 一级 和二级分类的标题
        String levelOneSubjectTitle = subjectExcelData.getLevelOneSubjectTitle();
        String levelTwoSubjectTitle = subjectExcelData.getLevelTwoSubjectTitle();
        //1、判断一级分类是否已经存在
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Subject::getTitle , levelOneSubjectTitle);
        queryWrapper.eq(Subject::getParentId , 0);
        Subject levelOneSubject = subjectMapper.selectOne(queryWrapper);
        if(levelOneSubject==null){
            //2、如果不存在： 将一级标题转为一级课程分类对象存到数据库表
            levelOneSubject = new Subject();
            levelOneSubject.setParentId(0+"");
            levelOneSubject.setTitle(levelOneSubjectTitle);
            subjectMapper.insert(levelOneSubject);
        }
        //3、获取一级分类的id： 二级分类保存时需要使用
        String levelOneSubjectId = levelOneSubject.getId();
        //4、判断当前一级分类的二级分类是否已存在
        queryWrapper.clear();//清空之前的条件
        queryWrapper.eq(Subject::getTitle , levelTwoSubjectTitle);
        queryWrapper.eq(Subject::getParentId , levelOneSubjectId);
        Integer count = subjectMapper.selectCount(queryWrapper);
        if(count==0){
            //如果不存在：转为二级分类对象存到 数据库表中
            Subject levelTwoSuject = new Subject();
            levelTwoSuject.setTitle(levelTwoSubjectTitle);
            levelTwoSuject.setParentId(levelOneSubjectId);
            subjectMapper.insert(levelTwoSuject);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("excel解析完毕");
    }
}
